# -*- coding: utf-8 -*-
"""
Wargame AI的“上层AI” —— 用于比赛的第5阶段想定2030331196和2030341296
2020-07
"""

__authur__ = 'Yu XH'

import copy
import time
from myAI.faction_ai_5_red_i import FactionAIRed as FactionAIRedI
from myAI.faction_ai_5_blue_i import FactionAIBlue as FactionAIBlueI


class FactionAI:
    def __init__(self, myAgent):
        self.color = myAgent.color
        self.scenario = myAgent.scenario
        self.max_step = 2880
        self.task = {}  # 公共变量，保存算子分配的任务信息{obj_id:['outputfire',param1,param2]}
        self.tactic = None  # 我方策略，'1-attack' | '2-defend'
        self.group_info = {}  # 保存算子分组信息 {group_name: {group_task: ['ToOccupy', city], obj_ids: [opr1, opr2]}}
        self.group_info_copy = {}  # 保存最初的算子分组，用于算子临时调离分组后的回归
        self.task_copy = {}  # factionAI运行中的操作对象，作用是减少对self.task的操作
        self.init_deploy_flag = True  # 开局部署兵力的标志
        self.last_observation = myAgent.scenario_info[-1]  # 保存上一步状态，便于和当前状态比较
        self.red_ai_i = FactionAIRedI(myAgent)
        self.blue_ai_i = FactionAIBlueI(myAgent)

    def reset(self):
        self.color = None
        self.scenario = None
        self.max_step = 2880
        self.task = {}
        self.tactic = None
        self.group_info = None
        self.task_copy = {}  # factionAI运行中的操作对象，作用是减少对self.task的操作
        self.last_observation = None  # 保存上一步状态，便于和当前状态比较

    def update(self, myAgent):
        try:
            while myAgent.thread_factionAI is not None:
                ############# 测试错误 ##########
                # time.sleep(0.5)
                # raise Exception('error')
                #################################

                if myAgent.observation['time']['cur_step'] <= self.last_observation['time']['cur_step']:
                    time.sleep(0.05)
                    continue

                if self.scenario == 2030331196:
                    if self.color == 0:
                        self.red_ai_i.update(self, myAgent)
                        # 写入任务
                        myAgent.agenda.ipcArgs.mutex_task.acquire()
                        self.task = copy.deepcopy(self.red_ai_i.task)
                        myAgent.agenda.ipcArgs.mutex_task.release()
                    else:
                        self.blue_ai_i.update(self, myAgent)
                        # 写入任务
                        myAgent.agenda.ipcArgs.mutex_task.acquire()
                        self.task = copy.deepcopy(self.blue_ai_i.task)
                        myAgent.agenda.ipcArgs.mutex_task.release()
                # 更新上一次态势信息
                self.last_observation = myAgent.observation
            print(f'game over: thread_factionAI exit')
        # 如果factionAI执行出错，捕获异常，线程变量置空
        except Exception as e:
            print(f'thread_factionAI failure:')
            myAgent.thread_factionAI = None
        else:
            pass
